﻿using SharpConfig;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BaiduActivePush
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static HttpClient client = new HttpClient();

        /// <summary>
        /// 产品名称
        /// </summary>
        static string ProductName = "BaiduActivePush";

        /// <summary>
        /// 产品版本
        /// </summary>
        static string Version = "1.0";

        /// <summary>
        /// 配置信息
        /// </summary>
        Configuration usercfg = new Configuration();

        static MainWindow()
        {
            client.DefaultRequestHeaders.UserAgent.ParseAdd(string.Format("{0}/{1}", ProductName, Version));
            client.DefaultRequestHeaders.Host = "data.zz.baidu.com";
        }

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            this.chk_IsDefaultSite.Click += Chk_IsDefaultSite_Click;
            this.cb_Site.SelectionChanged += Cb_Site_SelectionChanged;

        }


        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //配置加载
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "user.ini");
            if (System.IO.File.Exists(path))
            {
                usercfg = Configuration.LoadFromFile(path);
                SharpConfig.Section section = usercfg["General"];
                //this.tb_Site.ItemsSource = section["site"].StringValueArray;
                foreach (var item in section["site"].StringValueArray)
                {
                    this.cb_Site.Items.Add(item);
                }
                if (this.cb_Site.Items.Count > 0)
                {
                    if (this.cb_Site.Items.Contains(section["defaultsite"].StringValue))
                    {
                        this.cb_Site.SelectedItem = section["defaultsite"].StringValue;
                        this.chk_IsDefaultSite.IsChecked = true;
                    }
                    else
                    {
                        this.cb_Site.SelectedIndex = 0;
                    }
                }
                //this.tb_Site.Text = section["site"].StringValue;
                this.tb_Token.Text = section["token"].StringValue;
                this.chk_IsOriginal.IsChecked = section["type"].StringValue == "original";
            }
            else
            {
                usercfg = new Configuration();
            }
        }

        private void Cb_Site_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (usercfg == null || usercfg["General"] == null || this.cb_Site.SelectedItem == null)
                return;
            SharpConfig.Section section = usercfg["General"];
            this.chk_IsDefaultSite.IsChecked = this.cb_Site.SelectedItem.ToString() == section["defaultsite"].StringValue;

        }

        /// <summary>
        /// 添加网站
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddSite_Click(object sender, RoutedEventArgs e)
        {
            WindowAddSite win = new BaiduActivePush.WindowAddSite();
            win.Owner = this;
            if (win.ShowDialog() ?? false)
            {
                this.cb_Site.Items.Add(win.NewSite);
                btn_SaveConfig_Click(sender, e);
            }
        }


        /// <summary>
        /// 勾选默认网站
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chk_IsDefaultSite_Click(object sender, RoutedEventArgs e)
        {
            btn_SaveConfig_Click(sender, e);
        }

        /// <summary>
        /// 配置保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "user.ini");

                if (this.chk_IsDefaultSite.IsChecked ?? false)
                {
                    usercfg["General"]["defaultsite"].StringValue = this.cb_Site.Text;
                }

                usercfg["General"]["site"].StringValueArray = this.cb_Site.Items.SourceCollection.Cast<string>().ToArray();
                usercfg["General"]["token"].StringValue = this.tb_Token.Text;
                usercfg["General"]["type"].StringValue = this.chk_IsOriginal.IsChecked == true ? "original" : string.Empty;

                usercfg.SaveToFile(path);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 推送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Push_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string hosturl = "http://data.zz.baidu.com";
                string actionurl = "/urls";
                string param = string.Format("?site={0}&token={1}", this.cb_Site.Text, this.tb_Token.Text);
                if (this.chk_IsOriginal.IsChecked ?? false)
                {
                    param += "&type=original";
                }
                string url = hosturl + actionurl + param;

                StringContent str = new StringContent(this.tb_PostContentUrl.Text);

                var pushresponse = await client.PostAsync(url, str);
                if (pushresponse.StatusCode == System.Net.HttpStatusCode.OK)
                {

                }
                else
                {

                }
                this.tb_PostResponse.Text = await pushresponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("推送异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 界面链接打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

    }
}
